package com.heima.behavior.service.impl;

import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.util.AppUserThreadLocalUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.entity.ApUser;
import com.heima.user.util.AppThreadLocalUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.Date;


public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1. 校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2. 判断用户是否已经互相关注
        String like_hash_key = "USER_LIKES_" + dto.getArticleId();
        Boolean hasKey = stringRedisTemplate.opsForHash().hasKey(like_hash_key, user.getId() + "");

        //2.1 用户已点赞
        if (dto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
        }

        //2.2 用户已点赞 --- 取消点赞
        if (hasKey && dto.getOperation() == 1) {
            //2.2.1 删除缓存数据
            stringRedisTemplate.opsForHash().delete(like_hash_key,user.getId() + "");
            //2.2.2 删除mongodb数据
            Query query = Query.query(Criteria.where("userId").is(user.getId()).and("articleId").is(dto.getArticleId()));
            mongoTemplate.remove(query, ApFollowBehavior.class);
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
        }
        //2.3 用户未点赞
        if (!hasKey && dto.getOperation() == 0) {
            //2.3.1 保存关注数据到redis
            stringRedisTemplate.opsForHash().put(like_hash_key,user.getId() + "","1");

            //2.3.2 保存关注数据到数据库
            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setUserId(user.getId());
            apLikesBehavior.setCreatedTime(new Date());

            mongoTemplate.insert(apLikesBehavior);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
